package descentFly.away3D4.Generator
{
	import UIAway.uif_view;
	
	import UIFree.ObjectEvent;
	
	import UIUtils.uif_util;
	
	import away3d.entities.Mesh;
	
	import descentFly.app.df_events;
	import descentFly.away3D4.chips.df_chipAway;
	import descentFly.away3D4.chips.df_monster;
	import descentFly.away3D4.df_awaySpace;
	import descentFly.away3D4.df_baseSpaceElement;
	import descentFly.away3D4.df_points;
	import descentFly.chips.df_chip;
	import descentFly.df_optionsObject;
	import descentFly.df_spaceObject;
	import descentFly.df_utils;
	
	import flash.events.Event;
	import flash.events.IEventDispatcher;
	import flash.events.TimerEvent;
	import flash.utils.Timer;
	
	public class df_monsterGenerator extends df_basePoints {
		private var _timer		: Timer;
		private var _curPoint	: int;
		
		public function df_monsterGenerator(a_space: df_awaySpace, a_options: Object) {
			super(a_space, a_options);
		}
		
		override protected function initialize(): void {
			super.initialize();
			_curPoint 	= -1;
			_timer		= new Timer(options.period);
			_timer.addEventListener(TimerEvent.TIMER, doPeriod);
			_timer.start();

			Space.view.addEvent(uif_view.RENDERFREEZE, doRenderFreeze);
		}
		
		override protected function parseMesh(m:Mesh):Object {
			return df_utils.matToObject(m.transform);
		}
		
		override public function dispose():void {
			_timer.stop();
			super.dispose();
		}
		
		override protected function removeEvents():void {
			_timer.removeEventListener(TimerEvent.TIMER, doPeriod);			
			Space.view.removeEventListener(uif_view.RENDERFREEZE, doRenderFreeze);
		}
		
		protected function doRenderFreeze(e: ObjectEvent): void {
			if (e.object) _timer.stop();
			else _timer.start();
		}
		
		protected function doPeriod(e: Event): void {
			if ((count < options.maxMonsters) && !checkTotal()) createMonster();
		}
		
		protected function nextPoint(): Object {
			if (points.length > 0) {
				_curPoint = (_curPoint + 1) % points.length;
				return points[_curPoint];
			}
			return null;
		}
		
		protected function createMonster(): void {
			var p	: Object = nextPoint();
			if (p) addPoint(new (options.element.Class)(Space, uif_util.union(options.element.options, p)));
		}
	}
}